package net.csiit.tools.fileserver.client;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.csiit.tools.fileserver.client.dto.FileInfo;
import net.csiit.tools.fileserver.client.util.RestTemplateCreator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.*;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author adam
 * @date 2023-06-14
 */
@Slf4j
public class FileServerClient {

    private RestTemplate restTemplate;

    public FileServerClient() {
        this(60);
    }

    public FileServerClient(int timeoutSecond) {
        restTemplate = RestTemplateCreator.restTemplate(timeoutSecond, timeoutSecond);
    }

    public Map<String, FileInfo> getFileInfoMap(List<String> fileIds) {
        return getFileInfos(fileIds).stream().collect(Collectors.toMap(FileInfo::getFileId, v -> v, (v1, v2) -> v2));
    }

    public List<FileInfo> getFileInfos(List<String> fileIds) {
        if (CollectionUtils.isEmpty(fileIds)) {
            return Collections.emptyList();
        }

        String baseUrl = FileClientConfig.getFile_Server_Url();
        if (StringUtils.isEmpty(baseUrl)) {
            throw new IllegalStateException("Unknown file server url ! pls invoke [net.csiit.tools.fileserver.client.FileClientConfig.setFile_Server_Url] first !");
        }

        String url = baseUrl.concat("/fileserver/postFileInfos");

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json;charset=UTF-8");
        HttpEntity<String> entity = new HttpEntity(JSON.toJSONString(fileIds), headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        String json = response.getBody();

        if (response.getStatusCode() != HttpStatus.OK || StringUtils.isEmpty(json)) {
            log.error("Error invoke file info api ! code: {}, json: {}", response.getStatusCodeValue(), json);
            return Collections.emptyList();
        }

        JSONObject object = JSON.parseObject(json);
        JSONArray array = object.getJSONArray("content");
        if (array != null) {
            return array.toJavaList(FileInfo.class);
        }

        return Collections.emptyList();
    }
}
